package com.xy.shop.web.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xy.shop.common.annotation.OperLog;
import com.xy.shop.common.base.ResponseResult;
import com.xy.shop.common.constant.AppConstants;
import com.xy.shop.common.constant.CommonContants;
import com.xy.shop.common.constant.Rst;
import com.xy.shop.common.dtgrid.model.Pager;
import com.xy.shop.common.utils.ExportUtils;
import com.xy.shop.common.utils.FreeMarkerUtil;
import com.xy.shop.system.entity.User;
import com.xy.shop.web.dto.OrderWriteTemplate;
import com.xy.shop.web.service.BaseParamService;
import com.xy.shop.web.service.OrderWriteTemplateService;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zyy
 */
@RequestMapping("/web/temp/")
@Controller
public class OrderWriteTemplateController extends BaseController {

    @Resource
    private OrderWriteTemplateService orderWriteTemplateService;

    @Resource
    private BaseParamService baseParamService;

    static final String HTML="html";

    @GetMapping("getOrderTempUi")
    public String getOrderTempUi() {
        return "temp/temp_list";
    }

    /**
     * @Description 茶馆创房统计
     * @Author zyy
     **/
    @ResponseBody
    @RequestMapping(value = "/getTempList", method = RequestMethod.POST)
    public Map<String, Object> getTempList(String gridPager, HttpServletResponse response) {
        List<Map<String, Object>> list;
        try {
            Pager pager = JSON.parseObject(gridPager, Pager.class);
            // 判断是否包含自定义参数
            Map<String, Object> parameters = pager.getParameters();
            //getAppParams(parameters);
            Page<Object> page = PageHelper.startPage(pager.getNowPage(), pager.getPageSize());
            // 3、判断是否是导出操作
            if (pager.getIsExport()) {
                if (pager.getExportAllData()) {
                    // 3.1、导出全部数据
                    list = orderWriteTemplateService.queryListByPage(parameters);
                    if (list == null) {
                        list = new ArrayList<>();
                    }
                    ExportUtils.exportAll(response, pager, list);
                    return null;
                } else {
                    // 3.2、导出当前页数据

                    ExportUtils.export(response, pager);

                }
            } else {
                // 设置分页，page里面包含了分页信息
                list = orderWriteTemplateService.queryListByPage(parameters);
                if (list == null || list.size() == 0) {
                    list = new ArrayList<>();
                }
                return getReturnPage(pager, page, list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    @GetMapping("addUi")
    public String addUi(Model model) {
       String projectUrl= baseParamService.selectByPrimarycode(AppConstants.BaseParam.PROJECT_URL);
        model.addAttribute("projectUrl",projectUrl );
        return "temp/temp_add";
    }

    @OperLog(operModul = "添加模板", operDesc = "创建模板")
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Map<String, Object> create(OrderWriteTemplate template) {
        int count;
        if (Objects.isNull(template.getId())) {
            template.setCtime(new Date());
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            template.setUid(user.getId());
            count = orderWriteTemplateService.insertSelective(template);
        } else {
            count = orderWriteTemplateService.updateByPrimaryKeySelective(template);
        }
        if (count > 0) {
            return Rst.getReturnData(null, false, CommonContants.FAILURE_SUCCESS, "添加成功！");
        }
        //FreeMarkerUtil.CreateHtml();
        return Rst.getReturnData(null, false, CommonContants.FAILURE_1102, "添加数据失败！");
    }


    @OperLog(operModul = "添加模板", operDesc = "生成模板")
    @ResponseBody
    @RequestMapping(value = "/createTemp", method = RequestMethod.POST)
    public Map<String, Object> createTemp(OrderWriteTemplate template) {
        if (Objects.isNull(template.getId())) {
            return Rst.getReturnData(null, false, CommonContants.FAILURE_1102, "添加数据失败！");
        }
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        String tempName="order_template";
        OrderWriteTemplate  orderWriteTemplate= orderWriteTemplateService.selectByPrimaryKey(template.getId());
        String templateHtmlName=UUID.randomUUID().toString().replace("-","")+"-"+user.getId();
        String ctxPath = baseParamService.selectByPrimarycode(AppConstants.BaseParam.IMG_PATH_ROOT);
        String realPath = baseParamService.selectByPrimarycode(AppConstants.BaseParam.IMG_VISIT_PATH);
        String FilePath=ctxPath+"/"+HTML;
        List<OrderWriteTemplate> list=new ArrayList<>();
        list.add(orderWriteTemplate);
       boolean flag= FreeMarkerUtil.CreateHtml(orderWriteTemplate,list,tempName,FilePath,templateHtmlName);
       if(flag) {
           String url=realPath+"/"+HTML+"/"+templateHtmlName+".html";
           logger.info("createTemp url==="+url);
           template.setUrl(url);
           template.setAccessName(templateHtmlName);
         int count =  orderWriteTemplateService.updateByPrimaryKeySelective(template);
         if (count>0) {
             return   Rst.getReturnData(null, false, CommonContants.FAILURE_SUCCESS, "生成成功！");
         }
       }
        return   Rst.getReturnData(null, false, CommonContants.FAILURE, "生成失败！");
    }

    @OperLog(operModul = "添加模板", operDesc = "删除模板")
    @ResponseBody
    @RequestMapping(value = "/delTemp", method = RequestMethod.POST)
    public Map<String, Object> delTemp(OrderWriteTemplate template) {
        if (Objects.isNull(template.getId())) {
            return Rst.getReturnData(null, false, CommonContants.FAILURE, "删除失败！");
        }
        int count = orderWriteTemplateService.deleteByPrimaryKey(template.getId());
        if (count>0){
            return   Rst.getReturnData(null, true, CommonContants.FAILURE_SUCCESS, "删除成功！");
        }
        return   Rst.getReturnData(null, false, CommonContants.FAILURE, "生成失败！");
    }


}
